#!/usr/bin/env python
# encoding: utf-8
"""
#-------------------------------------------------------------------#
#                   CONFIDENTIAL --- CUSTOM STUDIOS                 #     
#-------------------------------------------------------------------#
#                                                                   #
#                   @Project Name : Globallawonline                #
#                                                                   #
#                   @File Name    : ErroPdfClean.py                      #
#                                                                   #
#                   @Programmer   : 李建                            #
#                                                                   #  
#                   @Start Date   : 2021/1/18 17:21                 #
#                                                                   #
#                   @Last Update  : 2021/1/18 17:21                 #
#                                                                   #
#-------------------------------------------------------------------#
# Classes: 该类用于清理目录下所有错误的pdf文件                                                          #
#                                                                   #
#-------------------------------------------------------------------#
"""
import datetime

import PyPDF2
import os
import re

from settings import FILES_DIR


class ErroPdfClean(object):
    def isValidPDF_pathfile(self, pathfile):
        bValid = True
        try:
            # PdfFileReader(open(pathfile, 'rb'))
            reader = PyPDF2.PdfFileReader(pathfile, strict=False)
            # if reader.getNumPages() < 1:  # 进一步通过页数判断。
            #     bValid = False
        except Exception as e:
            bValid = False
        return bValid

    def file_name(self, file_dir):
        for root, dirs, files in os.walk(file_dir, topdown=False):
            for pdffile in files:
                res_tr = r'''f.*?\.pdf'''  # 从网页源码中获取字符的正则表达式
                re_tr = re.findall(res_tr, pdffile, re.S)  # 利用正则表达式获取字符串并存到链表
                if len(re_tr):
                    pdffilepath = root + '\\' + pdffile
                    pdfright = self.isValidPDF_pathfile(pdffilepath)
                    if not pdfright:
                        with open('pdferror.txt', 'a', encoding='utf-8') as f:
                            f.write(str(datetime.datetime.now()) + ":"  + pdffilepath + '\n')
                        if os.path.exists(pdffilepath):
                            os.remove(pdffilepath)

    def epdfclean(self):
        print(str(datetime.datetime.now()) + "：开始进行错误pdf文件的清洗")
        self.file_name(FILES_DIR)
        print(str(datetime.datetime.now()) + "：错误pdf文件的清洗结束")
